package com.company.management.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.company.framework.pojo.PageResult;
import com.company.management.constant.Constants;
import com.company.management.domain.req.PerformanceEvaluationsReq;
import com.company.management.domain.req.PerformancePageReq;
import com.company.management.domain.rsp.PerformanceEvaluationsResp;
import com.company.management.domain.rsp.PerformanceUserResp;
import com.company.management.mapper.PerformanceEvaluationsMapper;
import com.company.management.modal.entity.PerformanceEvaluations;
import com.company.management.modal.entity.PerformanceEvaluationUsers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.sql.Wrapper;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author robet.li
 * @since 2025-03-02
 */
@Slf4j
@Service
public class PerformanceEvaluationsService extends ServiceImpl<PerformanceEvaluationsMapper, PerformanceEvaluations> {
    @Autowired
    private PerformanceEvaluationUsersService performanceevaluationUsersService;

    @Transactional(rollbackFor = Exception.class)
    public Integer saveResult(PerformanceEvaluationsReq req){
        PerformanceEvaluations bean = new PerformanceEvaluations();
        BeanUtils.copyProperties(req,bean);
        bean.setEvaluationContent(req.getContent().getBytes());
        bean.setCreateId(req.getUserId());
        bean.setCreateDateTime(new Date());
        boolean bSave = this.save(bean);
        if(bSave){
            String[] personIds = req.getPersonIds().split(",");
            for(String personId:personIds){
                PerformanceEvaluationUsers userBean = new PerformanceEvaluationUsers();
                userBean.setEvaluationId(bean.getEvaluationId());
                userBean.setUserId(Integer.parseInt(personId));
                performanceevaluationUsersService.save(userBean);
            }
            return 1;
        }else{
            return 0;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public Integer deletePerformance(PerformanceEvaluationsReq req){
        List<PerformanceEvaluationUsers> users = performanceevaluationUsersService.list(Wrappers.<PerformanceEvaluationUsers>lambdaQuery()
                .eq(PerformanceEvaluationUsers::getEvaluationId,req.getEvaluationId()));
        if (users!=null&& users.size()>0){
            performanceevaluationUsersService.remove(Wrappers.<PerformanceEvaluationUsers>lambdaQuery()
                    .eq(PerformanceEvaluationUsers::getEvaluationId,req.getEvaluationId())
                    .eq(PerformanceEvaluationUsers::getUserId,req.getPersonIds()));
        }else{
            boolean bDelete = this.removeById(req.getEvaluationId());
            if(bDelete){
                performanceevaluationUsersService.remove(Wrappers.<PerformanceEvaluationUsers>lambdaQuery()
                        .eq(PerformanceEvaluationUsers::getEvaluationId,req.getEvaluationId())
                        .eq(PerformanceEvaluationUsers::getUserId,req.getPersonIds()));
                return 1;
            }
        }
        return 1;
    }
    /**
     * 根据考核主题查询
     * @param evaluationTitle
     * @return
     */
    public PerformanceEvaluations detailByEvaluationTitle(String evaluationTitle) {
        List<PerformanceEvaluations> performanceEvaluations = this.list(Wrappers.<PerformanceEvaluations>lambdaQuery()
                .eq(PerformanceEvaluations::getEvaluationTitle,evaluationTitle));
        if (performanceEvaluations!=null&& performanceEvaluations.size()>0){
            PerformanceEvaluations bean = performanceEvaluations.get(0);
            return bean;
        }else{
            return null;
        }
    }
    public PerformanceEvaluationsResp detail(PerformanceEvaluationsReq req) {
        PerformanceEvaluationsResp resp = new PerformanceEvaluationsResp();
        PerformanceEvaluations bean = this.getById(req.getEvaluationId());
        List<PerformanceUserResp> userRespList = performanceevaluationUsersService.getPerformanceUserList(req);
        if(bean!=null && userRespList!=null){
            BeanUtils.copyProperties(bean,resp);
            resp.setDeptUserList(userRespList);
            try {
                resp.setContent(new String(bean.getEvaluationContent(), Constants.GBK));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            List<String> names = userRespList.stream().map(PerformanceUserResp::getName)
                    .collect(Collectors.toList());
            resp.setPersons(StringUtils.join(names.toArray(),","));
            List<Integer> ids = userRespList.stream().map(PerformanceUserResp::getId)
                    .collect(Collectors.toList());
            resp.setPersonIds(StringUtils.join(ids.toArray(),","));
            return resp;
        }else{
            return null;
        }
    }
    public PageResult<PerformanceEvaluationsResp> getPerformanceList(PerformancePageReq req){
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        req.setUserId(req.getUserId());
        List<PerformanceEvaluationsResp> list = this.baseMapper.getPerformanceList(req);
        list.forEach(item->{
            try {//Constants.GBK
                //item.setContent(new String(item.getEvaluationContent(), "UTF-8"));
                item.setContent(new String(item.getEvaluationContent(), Constants.GBK));
            } catch (UnsupportedEncodingException e) {
            }
        });
        PageInfo<PerformanceEvaluationsResp> page = new PageInfo<>(list);
        return new PageResult<>(list, page.getTotal());
    }
}
